﻿'use strict';

//Global Scope - Everyone shares that. VS Local Scope 
//Wrapper Objects

// AJAX - Sending request to and from a server or database Asynchronously JSON is that type of information that an AJAX request will recieve back. 

// Query String is how you can send data on a GET request. 

// Object Literal Notation - When you create an object it comes with a built in prototype e.g. "toString" 
var ticketingApp = (function (Array) {


    //  var ticketingApp = {};
    var tickets = [];
    var url = "https://rosterapp.firebaseio.com/.json";

    //jQuery GET call for AJAX
    var loadTickets = function () {
        $.ajax({
            url: url,
            type: "GET",
            
        }).done(function (data) {
            for (var i in data) {
                var ticket = data[i];
                tickets.push(ticket)
            }
            displayTickets();
        })
    }

    var CreateTicket = function (issue, priority, name, date) {
        this.issue = issue;
        this.priority = priority;
        this.name = name;
        this.date = new Date();
    };

    var sendTicket = function () {

        var issue = document.getElementById('issue').value
        var priority = document.getElementById('priority').value
        var name = document.getElementById('name').value

        var t1 = new CreateTicket(issue, priority, name);

        // console.log(ticketingApp.tickets);



        // jQuery AJAX call!!!
        $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(t1),
            contentType: 'application/json',
            dataType: "json"
            
        }).done(function (data) {
            alert(data.name);
            tickets.push(t1);
            displayTickets(); // come back here
        });
    };

    var displayTickets = function () {
        var h = '<table class="table table-bordered table-striped">';
        h += '<tr>';
        h += '<th> Issue </th>';
        h += '<th> Priority </th>';
        h += '<th> Name </th>';
        h += '<th> Date </th>';
        h += '</tr>';

        // This is the method invokation pattern
        for (var i in tickets) {
            //if (!t.hasOwnProperty(i)) {
            //    continue;
            //}

            var t = tickets[i];
            h += '<tr>';
            h += '<td>' + t.issue + '</td>'
            h += '<td>' + t.priority + '</td>'
            h += '<td>' + t.name + '</td>'
            h += '<td>' + t.date + '</td>'
            h += '</tr>';
        };
        h += '</table>';
        document.getElementById('tickets').innerHTML = h;
    };

    loadTickets();
    return {
        sendTicket: sendTicket,
        displayTickets: displayTickets,

    }
})(Array);

